import { plainToClass } from "class-transformer"
import { validate } from "class-validator"
import { Response } from "express"

export abstract class CommonClass {
  // 类校验
  public async Validate(skip = false): Promise<string[]> {
    const errors = await validate(this, {
      skipUndefinedProperties: skip,
      skipNullProperties: skip,
      skipMissingProperties: skip
    })
    const errMsgs: string[] = errors.map(item => {
      return Object.values(item.constraints || {})
    }).flat()
    return errMsgs
  }

  // plainObj转类
  static plainToClass<T>(cls: new () => T, plainObj: object): T {
    return plainToClass(cls, plainObj)
  }
}


export class ResponseClass {
  static sendRes(data: any, res: Response) {
    res.send({
      code: 200,
      success: true,
      data: data,
      message: '成功'
    })
  }

  static sendErr(msg: string | string[], res: Response) {
    res.send({
      code: 500,
      success: false,
      data: null,
      message: Array.isArray(msg) ? msg.join(',') : msg || '失败'
    })
  }
}